const sql = require('../../sql/sqlConfig');
const express = require('express');
let router = express.Router();
const pagination = require('../../util/page');
const tokenObj = require('../../util/jwt');
let myToken = new tokenObj();

//查商品类型
router.get('/type', function (req, res, next) {
    let option = "select * from `product_type` where `uping` = 1";
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'查询失败'+err});
        res.send({errCode:0,message:'查询产品类型成功',result:rows});
    })
});

//查用户等级
function getUserLevel(id,fn){
    let option = "select sum(`num`) as total from `order` where `order_payment_status`=1 and `pid`="+id+" group by `pid`";
    sql.query(option, function (err, rows) {
        if (err) return fn(0,err);
        let count = rows.length>0?rows[0].total:0;//用户分享成功的单数
        let option1 = "select * from `level_setting` where `order_num`<="+count;//找到1、2级，用户分享的单子都比这几级大
        sql.query(option1, function (err1, rows1) {
            if (err1) return fn(0,err1);
            let result = {};
            let maxNum = Math.max.apply(Math, rows1.map(function(val) {return val.order_num}));//找到2级
            rows1.forEach((val,index,arr)=>{
                if(val.order_num==maxNum)
                    return result=val;
            });
            return fn(1,result)
        })
    })
}

//查商品列表
router.get('/',function(req,res) {
    let typeId = req.query.typeId;
    let countPageSql,option;
    if(typeId==undefined){
        countPageSql = "select count(`id`) as total from `product` where `upper_shelf`=1";
        option = "select p.*,t.`name` as `type_name` from `product` as p join `product_type` as t on p.`type_id`=t.`id` where p.`upper_shelf`=1 limit ";
    }else{
        countPageSql = "select count(`id`) as total from `product` where `upper_shelf`=1 and `type_id`="+typeId;
        option = "select p.*,t.`name` as `type_name` from `product` as p join `product_type` as t on p.`type_id`=t.`id` where p.`type_id`="+typeId+" and p.`upper_shelf`=1 limit ";
    }
    let page = req.query.page;
    pagination(countPageSql,page,option,function (result) {
        if(result.errCode==9){
            return res.send(result)
        }else if(result.errCode==0) {
            let list = result.data.result;
            let idList = list.map((val, index, arr) => {return val.id});
            let getSaleSql = "select `product_id`, sum(`num`) as total from `order` where `order_payment_status`=1 and `product_id` in (" + [...idList] + ") group by `product_id`";
            sql.query(getSaleSql, function (err, rows) {
                if (err) return res.send({errCode: -9999, message: '查询失败' + err});
                if(rows.length>0) {
                    rows.forEach((val, i, arr) => {
                        list.forEach((list, index, array) => {
                            if (list.id == val.product_id) {
                                list.sale = val.total;
                                return
                            }
                            if (list.sale == undefined) list.sale = 0;
                        })
                    });
                }else {
                    list.forEach((val,index,arr)=>{
                        val.sale=0
                    })
                }
               //校验token
                let token = req.headers.token;
                let userId = null;
                myToken.checkToken(token,function(flag) {
                    if (!flag) { //没有登录的
                        result.data.result = list.map((val, index, arr) => {
                            return {
                                "id": val.id,
                                "pic": val.pic,
                                "name": val.name,
                                "disc": val.disc,
                                "price": val.price,
                                "sale": val.sale
                            }
                        });
                        return res.send(result)
                    }else{//有token的
                        userId = flag;
                        getUserLevel(userId,function (flag,info) {//查用户分销商等级
                            if(!flag) return res.send({errCode: -9999, message: '操作数据库失败' + info});
                            let level = info.level;
                            let proportion = info.proportion;
                            result.data.result = list.map((val, index, arr) => {
                                return {
                                    "id": val.id,
                                    "pic": val.pic,
                                    "name": val.name,
                                    "disc": val.disc,
                                    "price": val.price,
                                    "sale": val.sale,
                                    "level":level,
                                    "commission":Math.floor(((val.price-val.principal)*(proportion.replace("%","")/100)) * 100) / 100
                                }
                            });
                            return res.send(result)
                        })
                    }
                });
            })
        }
    });
});

//搜索商品根据商品名
router.get('/search',function(req,res) {
    let searchKey = req.query.search;
    let countPageSql,option;
    if(typeof(searchKey)=="string" && searchKey.length>0){//模糊查询
        countPageSql = "select count(`id`) as total from `product` where `upper_shelf`=1 and `name` like '%"+searchKey+"%'";
        option = "select p.*,t.`name` as `type_name` from `product` as p join `product_type` as t on p.`type_id`=t.`id` where p.`name` like '%"+searchKey+"%' and p.`upper_shelf`=1 limit ";
    }else{//查询全部商品数据
        countPageSql = "select count(`id`) as total from `product` where `upper_shelf`=1";
        option = "select p.*,t.`name` as `type_name` from `product` as p join `product_type` as t on p.`type_id`=t.`id` where p.`upper_shelf`=1 limit ";
    }
    let page = req.query.page;
    pagination(countPageSql,page,option,function (result) {
        if(result.errCode==9){
            result.message = "没有数据了喔";
            return res.send(result)
        }else if(result.errCode==0) {
            let list = result.data.result;
            let idList = list.map((val, index, arr) => {return val.id});
            let getSaleSql = "select `product_id`, sum(`num`) as total from `order` where `order_payment_status`=1 and `product_id` in (" + [...idList] + ") group by `product_id`";
            sql.query(getSaleSql, function (err, rows) {
                if (err) return res.send({errCode: -9999, message: '查询失败' + err});
                if(rows.length>0) {
                    rows.forEach((val, i, arr) => {
                        list.forEach((list, index, array) => {
                            if (list.id == val.product_id) {
                                list.sale = val.total;
                                return
                            }
                            if (list.sale == undefined) list.sale = 0;
                        })
                    });
                }else {
                    list.forEach((val,index,arr)=>{
                        val.sale=0
                    })
                }
                //校验token
                let token = req.headers.token;
                let userId = null;
                myToken.checkToken(token,function(flag) {
                    if (!flag) { //没有登录的
                        result.data.result = list.map((val, index, arr) => {
                            return {
                                "id": val.id,
                                "pic": val.pic,
                                "name": val.name,
                                "disc": val.disc,
                                "price": val.price,
                                "sale": val.sale
                            }
                        });
                        return res.send(result)
                    }else{//有token的
                        userId = flag;
                        getUserLevel(userId,function (flag,info) {//查用户分销商等级
                            if(!flag) return res.send({errCode: -9999, message: '操作数据库失败' + info});
                            let level = info.level;
                            let proportion = info.proportion;
                            result.data.result = list.map((val, index, arr) => {
                                return {
                                    "id": val.id,
                                    "pic": val.pic,
                                    "name": val.name,
                                    "disc": val.disc,
                                    "price": val.price,
                                    "sale": val.sale,
                                    "level":level,
                                    "commission":Math.floor(((val.price-val.principal)*(proportion.replace("%","")/100)) * 100) / 100

                                }
                            });
                            return res.send(result)
                        })
                    }
                });
            })
        }
    });
});

//商品详情
router.get('/detail',function(req,res) {
    let prodictId = req.query.productId;
    let option = "select * from `product` where `id` = "+prodictId;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        if(rows.length==0) res.send({errCode:9,message:'没有该商品信息'});
        let productDetail = rows;
        let getSaleSql = "select `product_id`, sum(`num`) as total from `order` where `order_payment_status`=1 and `product_id` = " + prodictId + " group by `product_id`";
        sql.query(getSaleSql, function (err, rows) {
            if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
            productDetail[0].sale = rows.length==0?0:rows[0].total;
            //做token校验
            let token = req.headers.token;
            let userId = null;
            myToken.checkToken(token,function(flag) {
                if (!flag) { //没有登录的
                    let result = productDetail.map((val,index,arr)=>{
                        return {
                            "id": val.id,
                            "pic": val.pic,
                            "name": val.name,
                            "disc": val.disc,
                            "price": val.price,
                            "detail": val.detail,
                            "type_id": val.type_id,
                            "sale": val.sale
                        }
                    });
                    return res.send({errCode:0,message:'查询成功',result:result[0]})
                } else {//有token的
                    userId = flag;
                    getUserLevel(userId,function (flag,info) {//查用户分销商等级
                        if(!flag) return res.send({errCode: -9999, message: '操作数据库失败' + info});
                        let level = info.level;
                        let proportion = info.proportion;
                        let result = productDetail.map((val, index, arr) => {
                            return {
                                "id": val.id,
                                "pic": val.pic,
                                "name": val.name,
                                "disc": val.disc,
                                "price": val.price,
                                "detail": val.detail,
                                "type_id": val.type_id,
                                "sale": val.sale,
                                "level":level,
                                "commission":Math.floor(((val.price-val.principal)*(proportion.replace("%","")/100)) * 100) / 100
                            }
                        });
                        return res.send({errCode:0,message:'查询成功',result:result[0]})
                    })
                }
            })
        })
    })
});


module.exports = router;


